package com.winning.gjhlht.ihe.hl7ClientService.data.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.framework.server.db.bean.PageBean;
import com.framework.server.db.bean.PageQueryBean;
import com.framework.server.manager.SQLConfigLoader;
import com.winning.common.beans.ihe.IHERequestBodyBean;
import com.winning.common.beans.xmlTemp.XMLTempBeanManager;
import com.winning.common.beans.xmlTemp.XMLTempConfigBean;
import com.winning.common.data.service.PlatBasicDataService;
import com.winning.common.tools.XMLTool;
import com.winning.core.net.CXFWebserviceClent;
import com.winning.gjhlht.ihe.hl7ClientService.data.dao.inter.IHEDataDaoInter;

/**
 * 类名称：IHEGrxxDataService
 * 类描述：   互联互通个人信息服务
 * 创建人：zhaqiang
 * 创建时间：2017-2-28 下午2:13:28
 * 修改人：zhaqiang
 * 修改时间：2017-2-28 下午2:13:28
 * 修改备注：
 */
@Service(value = "com.winning.gjhlht.ihe.hl7ClientService.data.service.IHEGrxxDataService")
public class IHEGrxxDataService extends IHEBaseDataService {

    private static Logger LOGGER = Logger.getLogger("pbsLoger");

    //张家港患者注册服务ID
    private static final String ZJG_HZZC_SERVICE_ID = "GRZC_ZJG_TEMP_002";


    @Autowired
    private PlatBasicDataService platBasicDataService = null;

    @Autowired
    private IHEDataDaoInter iheDataDao = null;


    /**
     * 上传一个患者的基本信息
     * 方法名称: uploadHzxx
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-2-28/下午2:17:11<br/>
     */
    public JSONObject uploadHzxx(String zjhm, String grjbxxbsh) {
        JSONObject rs = new JSONObject();

        try {
            //where条件
            String tjSQL = " AND ZJHM = '" + zjhm + "' AND GRJBXXBSH = '" + grjbxxbsh + "'";

            boolean tag = uploadHlhtService(tjSQL, ZJG_HZZC_SERVICE_ID, platBasicDataService, iheDataDao);

            if (tag) {
                //查询上传结果
                String sql = "select * from IHE_GR_JBXX_LOG where JBXXBSH = '" + grjbxxbsh + "' and ZJHM = '" + zjhm + "'";

                //获取数据源
                String dbDataSourceID = getDBDataSouorceID(ZJG_HZZC_SERVICE_ID);

                JSONObject json = iheDataDao.executSQLForJSONObject(sql, null, dbDataSourceID);

                if (json != null) {
                    if (json.getString("ZCJG").equals("AA")) {
                        rs.put("RS", "TRUE");
                    } else {
                        rs.put("RS", "FALSE");
                        rs.put("INFO", json.getString("ZCJGSM"));
                    }
                } else {
                    rs.put("RS", "FALSE");
                    rs.put("INFO", "注册结果未保存到本地系统!");
                }
            } else {
                rs.put("RS", "FALSE");
                rs.put("INFO", "注册流程出错!");
            }
        } catch (Exception e) {
            LOGGER.info(e, e.fillInStackTrace());

            rs.put("RS", "FALSE");

            rs.put("INFO", e.fillInStackTrace());

        }

        return rs;
    }


    /**
     * 方法名称: queryJBXXZCJG
     *
     * @param 获取患者信息注册结果信息
     * @param ZCLX         注册类型标识
     *                     创建时间：2017-1-7/下午1:29:23<br/>
     * @return List<JSONObject>  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     */
    public JSONObject queryJBXXZCJG(int ZCLX, String JGDM, String startDate, String endDate, String ZCJG, int pageNumber, int pageSize, String ZJHM) {

        LOGGER.info("--> 进入 queryJBXXZCJG 方法 ");
        LOGGER.info("--> ZCLX = [" + ZCLX + "] , JGDM = [" + JGDM + "] ,startDate = [" + startDate + "] ,endDate = [" + endDate + "] ,ZCJG = [" + ZCJG + "] , ZJHM = [" + ZJHM + "]");

        String sql = "";

        String totalSql = "";

        //数据源
        String dbDataSourceID = "";

        try {

            //获取配置信息
            Map<String, XMLTempConfigBean> XMLTempConfigBeanMap = XMLTempBeanManager.getInstance().getXMLTempConfigBeanMap();

            //获取患者个人信息注册结果
            if (ZCLX == 1) {
                sql = "select * from (select YLJGDM,JBXXBSH,ZJHM,XM,GJPTBSH, ZCRQ ,ZCJG,ZCLX,ZCJGSM,ROWNUM as RN from IHE_GR_JBXX_LOG where ROWNUM<= ?";

                totalSql = "select * from IHE_GR_JBXX_LOG where 1=1";
                // 获取数据源
                for (Entry<String, XMLTempConfigBean> entity : XMLTempConfigBeanMap.entrySet()) {
                    //一个模板接口配置任务
                    XMLTempConfigBean xmlTempConfigBean = entity.getValue();

                    //获取个人信息注册数据源
                    if (xmlTempConfigBean.getServiceID().equals(ZJG_HZZC_SERVICE_ID)) {
                        dbDataSourceID = xmlTempConfigBean.getDbDataSourseID();
                        break;
                    }
                }
            }

            //添加查询条件
            if (!JGDM.equals("") && JGDM != null) {
                sql += "and YLJGDM = '" + JGDM + "'";

                totalSql += "and YLJGDM = '" + JGDM + "'";
            }

            if (!ZCJG.equals("") && ZCJG != null) {
                sql += "and ZCJG = '" + ZCJG + "'";

                totalSql += "and ZCJG = '" + ZCJG + "'";
            }

            if (!ZJHM.equals("") && ZJHM != null) {
                sql += "and ZJHM = '" + ZJHM + "'";

                totalSql += "and ZJHM = '" + ZJHM + "'";
            }

            if (!startDate.equals("") && startDate != null && !endDate.equals("") && endDate != null) {

                sql += "and ZCRQ between '" + startDate + "' and '" + endDate + "'";

                totalSql += "and ZCJG = '" + ZCJG + "'";
            }
            sql += "order by ZCRQ desc ) where RN >=?";


            //总记录数
            int total = 0;
            totalSql = "select count(*) as TOTALCOUNT from (" + totalSql + ")";

            LOGGER.info("--> 数据源 = " + dbDataSourceID);
            LOGGER.info("--> totalSql = " + totalSql);

            total = iheDataDao.queryTotalDataCount(totalSql, "TOTALCOUNT", dbDataSourceID);

            LOGGER.info("--> total = " + total);

            //获取返回结果
            List<JSONObject> result = iheDataDao.getJBXXResgiterResult(sql, new Object[]{pageSize * pageNumber, (pageNumber - 1) * pageSize}, dbDataSourceID);

            JSONObject json = new JSONObject();
            json.put("rows", result);
            json.put("total", total);

            return json;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.toString());
            return null;
        }
    }


    /**
     * 获取基本信息注册结果数据统计
     * 方法名称: queryJBXXZCJGCount
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zq@winning.com.cn<br/>
     * 创建时间：2017-1-7/下午2:04:23<br/>
     */
    public JSONObject queryJBXXZCJGCount() {
        String sql = "";

        //数据源
        String dbDataSourceID = "";

        JSONObject json = new JSONObject();

        try {
            //获取配置信息
            Map<String, XMLTempConfigBean> XMLTempConfigBeanMap = XMLTempBeanManager.getInstance().getXMLTempConfigBeanMap();

            //获取数据源
            for (Entry<String, XMLTempConfigBean> entity : XMLTempConfigBeanMap.entrySet()) {
                //一个模板接口配置任务
                XMLTempConfigBean xmlTempConfigBean = entity.getValue();

                //获取个人信息注册数据源
                if (xmlTempConfigBean.getServiceID().equals(ZJG_HZZC_SERVICE_ID)) {
                    dbDataSourceID = xmlTempConfigBean.getDbDataSourseID();
                    sql = "select (select count(*)  from IHE_GR_JBXX_LOG) as GRJBXXZCZS  , (select count(*)  from IHE_GR_JBXX_LOG where ZCJG = 'AA') as GRJBXXZCCGZS , " +
                            "(select count(*)  from IHE_GR_JBXX_LOG where ZCJG = 'AE')  as GRJBXXZCSBZS , " +
                            "(select to_char(TABLE_TIME, 'YYYY-MM-DD HH:MI:SS') from SYS_SJSC_TABLE where TABLE_NAME = '" + xmlTempConfigBean.getServiceID() + "%DA_GR_JBXX') AS GRZLGXSJ from SYS_SJSC_TABLE";

                    JSONObject result = iheDataDao.getJBXXResgiterCount(sql, null, dbDataSourceID);

                    json.put("GR", result);
                }
            }
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.toString());
            return null;
        }
    }

    /**
     * 获取个人信息上传统计信息
     * 方法名称: getHzxxSctjInfo
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-2-28/下午1:32:47<br/>
     */
    public JSONObject getHzxxSctjInfo() {
        JSONObject result = new JSONObject();

        try {
            String sql = SQLConfigLoader.getSQLByID("IHE_Client_CountHzxx_SCTJ");

            //获取数据源
            String dataSourseID = getDBDataSouorceID(ZJG_HZZC_SERVICE_ID);


            result = iheDataDao.executSQLForJSONObject(sql, null, dataSourseID);

            result.put("XCZXSJ", getTimeByTrigger(ZJG_HZZC_SERVICE_ID));

        } catch (Exception e) {
            LOGGER.error(e, e.fillInStackTrace());
        }

        return result;
    }


    /**
     * 分页查询患者信息
     * 方法名称: pageQueryHzxxInfo
     *
     * @param
     * @return JSONObject  返回类型说明<br/>
     * @throws <br/>
     * @author zhaqiang@winning.com.cn<br/>
     * 创建时间：2017-2-27/下午1:54:01<br/>
     */
    public JSONObject pageQueryHzxxInfo(Map<String, Object> param, int pageNumber, int pageSize) {

        JSONObject result = new JSONObject();

        PageQueryBean pqb = null;


        try {
            String querySQL = "";

            String sczt = param.get("sczt").toString();

            String orderStr = "";

            if (sczt.equals("3")) {
                //未上传查询
                querySQL = SQLConfigLoader.getSQLByID("IHE_Client_QueryHzxx_WSC");

                //拼接条件
                if (param.containsKey("jgbm")) {
                    querySQL += " and YLJGDM = '" + param.get("jgbm") + "'";
                }
                if (param.containsKey("zjhm")) {
                    querySQL += " and ZJHM = '" + param.get("zjhm") + "'";
                }
                if (param.containsKey("startDate")) {
                    querySQL += " and TBRQ > to_date('" + param.get("startDate") + "','YYYY-MM-DD')";
                }
                if (param.containsKey("endDate")) {
                    querySQL += " and TBRQ < to_date('" + param.get("endDate") + "','YYYY-MM-DD')";
                }
                if (param.containsKey("xm")) {
                    querySQL += " and XM like '%" + param.get("xm") + "%'";
                }

                orderStr = null;
            } else {
                //上传查询
                querySQL = SQLConfigLoader.getSQLByID("IHE_Client_QueryHzxx_YSC");

                //凭借条件
                if (param.containsKey("jgbm")) {
                    querySQL += " and YLJGDM = '" + param.get("jgbm") + "'";
                }
                if (param.containsKey("zjhm")) {
                    querySQL += " and ZJHM = '" + param.get("zjhm") + "'";
                }
                if (param.containsKey("startDate")) {
                    querySQL += " and ZCRQ > to_date('" + param.get("startDate") + "','YYYY-MM-DD')";
                }
                if (param.containsKey("endDate")) {
                    querySQL += " and ZCRQ < to_date('" + param.get("endDate") + "','YYYY-MM-DD')";
                }
                if (param.containsKey("xm")) {
                    querySQL += " and XM like '%" + param.get("xm") + "%'";
                }
                if (sczt.equals("1")) {
                    querySQL += " and ZCJG = 'AA' ";
                }
                if (sczt.equals("2")) {
                    querySQL += " and ZCJG = 'AE' ";
                }

                orderStr = " ORDER BY ZCRQ DESC";
            }

            //获取数据源
            String dataSourseID = getDBDataSouorceID(ZJG_HZZC_SERVICE_ID);


            LOGGER.info("-->分页查询个人信息的SQL：" + querySQL);

            //做分页处理
            PageBean pageBean = new PageBean();

            pageBean.setPageNum(pageNumber);

            //必须要填的
            pageBean.setPageSize(pageSize);

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

            LOGGER.info("--> 开始执行SQL 开始时间：" + formatter.format(new Date().getTime()));

            pqb = iheDataDao.executeSQLByPage(pageBean, querySQL, orderStr, dataSourseID);


            LOGGER.info("--> 结束执行SQL 结束时间：" + formatter.format(new Date().getTime()));

            if (pqb.getDataSet() != null) {
                //数据库查询结果集采用XML结构返回
                String resultXML = pqb.getDataSet().toString();

                JSONArray array = paraseXMLToJSONArray(resultXML);

                result.put("rows", array);
                result.put("total", pqb.getPageBean().getRecordCount());
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }

        return result;
    }

}
